package com.oneguy.libupdate;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;

import java.io.File;

/**
 * Created by ZuoShu on 17/1/12.
 */
public class DownloadActivity extends Activity {
    private static final String TAG = "DownloadActivity";
    ProgressDialog loadingDialog;
    Handler mainHandler;
    AlertDialog downloadFailDialog;
    AlertDialog exitDialog;

    String url;
    String saveDir;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainHandler = new Handler();
        url = getIntent().getStringExtra("url");

        saveDir = Environment.getExternalStorageDirectory() + "/GoldenPeas/update/";

        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            exitDialog = buildExitDialog(Downloader.ERROR_FILE);
            exitDialog.show();
            return;
        }

        initDialogs();

        startDownload();

        LogHelper.warn(TAG, "getFilesDir:" + getFilesDir().getPath());
    }

    private void startDownload() {
        LogHelper.warn(TAG, "start download:" + url + " -> " + saveDir);
        Downloader.getInstance().stop();
        int result = Downloader.getInstance().start(url, saveDir, new Listener());
        LogHelper.warn(TAG, "start download:" + result);
        if (result != Downloader.START_SUCCESS) {
            if (downloadFailDialog != null && downloadFailDialog.isShowing()) {
                downloadFailDialog.dismiss();
            }
            downloadFailDialog = buildFailDialog(result);
            downloadFailDialog.show();
        }
    }

    private void initDialogs() {
        loadingDialog = ProgressDialog.show(
                this,
                "",
                getString(R.string.download_progress, 0),
                false,
                false
        );
    }

    private void exitApp() {
        Intent home = new Intent(Intent.ACTION_MAIN);
        home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        home.addCategory(Intent.CATEGORY_HOME);
        startActivity(home);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }

        if (downloadFailDialog != null) {
            downloadFailDialog.dismiss();
        }
        finish();
    }

    private AlertDialog buildFailDialog(int code) {
        int message;
        switch (code) {
            case Downloader.ERROR_NETWORK:
                message = R.string.download_error_network;
                break;
            case Downloader.ERROR_NO_SPACE:
                message = R.string.download_error_space;
                break;
            case Downloader.ERROR_FILE:
                message = R.string.download_error_permission;
                break;
            default:
                message = R.string.download_error;
                break;
        }
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setMessage(message)
                .setPositiveButton(R.string.retry, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startDownload();
                    }
                })
                .setCancelable(false)
                .create();
        return dialog;
    }

    private AlertDialog buildExitDialog(int code) {
        int message;
        switch (code) {
            case Downloader.ERROR_NETWORK:
                message = R.string.download_error_network;
                break;
            case Downloader.ERROR_NO_SPACE:
                message = R.string.download_error_space;
                break;
            case Downloader.ERROR_FILE:
                message = R.string.download_error_permission;
                break;
            default:
                message = R.string.download_error;
                break;
        }
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setMessage(message)
                .setPositiveButton(R.string.exit, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        exitApp();
                    }
                })
                .setCancelable(false)
                .create();
        return dialog;
    }

    private class Listener implements Downloader.DownloadListener {

        @Override
        public void onSuccess(final String filePath) {
            LogHelper.warn(TAG, "download success:" + filePath);
            installApp(new File(filePath));
        }

        @Override
        public void onFail(final int code) {
            LogHelper.warn(TAG, "download fail:" + code);
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (downloadFailDialog != null && downloadFailDialog.isShowing()) {
                        downloadFailDialog.dismiss();
                    }
                    downloadFailDialog = buildFailDialog(code);
                    downloadFailDialog.show();
                }
            });
        }

        @Override
        public void onProgress(final long total, final long current) {
            LogHelper.warn(TAG, "download progress total:" + total + " current:" + current);
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (loadingDialog != null) {
                        int percent = 0;
                        if (total != 0) {
                            percent = (int) (current * 100l / total);
                        }
                        loadingDialog.setMessage(getString(R.string.download_progress, percent));
                    }
                }
            });
        }

        private void installApp(File appFile) {
            Uri uri = Uri.fromFile(appFile);
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, "application/vnd.android.package-archive");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }

}
